﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using TeamWork_Server.HTTP;
using Newtonsoft.Json;

namespace TeamWork_Server
{
    public class CodeUpdateService
    {
        public CodeUpdateService()
        {
        }

        private string RemoveControlCharacters(string inString)
        {
            if (inString == null) return null;

            StringBuilder newString = new StringBuilder();
            char ch;

            for (int i = 0; i < inString.Length; i++)
            {

                ch = inString[i];

                if (!char.IsControl(ch))
                {
                    newString.Append(ch);
                }
            }
            return newString.ToString();
        }

        private List<twlib.CodeUpdateTemplate> CodeUpdates = new List<twlib.CodeUpdateTemplate>();

        public void service_HttpContextReceived(object sender, HttpContextReceivedEventArgs e)
        {
            if (e.Context.Request.Headers["packet_type"] == "CodeSubmit")
            {
                string fName = e.Context.Request.Headers["code_file"];
                string author = e.Context.Request.Headers["author"];
                StreamReader reader = new StreamReader(e.Context.Request.InputStream);
                string code = reader.ReadToEnd();
                e.Context.Response.Close();

                twlib.CodeUpdateTemplate temp = new twlib.CodeUpdateTemplate();
                temp.Author = author;
                temp.File = fName;
                temp.Code = code;
                temp.Date = DateTime.UtcNow.ToBinary();
                CodeUpdates.Add(temp);
                Log.Info("Received a new code update for file '" + fName + "'.");
                ChatService.BroadcastMessage("[SERVER]: Received a new code update for file '" + fName + "', from: " + author + ".");
            }
            if (e.Context.Request.Headers["packet_type"] == "CodeReview")
            {
                string fName = e.Context.Request.Headers["file_name"];
               StreamWriter writer = new StreamWriter(e.Context.Response.OutputStream);
               var updates = from c in CodeUpdates.ToArray() where c.File == fName orderby c.Date select c;
               List<twlib.CodeUpdateTemplate> u2 = updates.ToList();
               string data = JsonConvert.SerializeObject(u2, Formatting.Indented);
               writer.Write(data);
               writer.Flush();
               e.Context.Response.Close();
            }
        }
    }
}
